// object encapsulating a time interval, specified by two HourMinute objects

module.exports = (function() {
  "use strict";

  var HourMinute = require("../lib/hourMinute");



  // constructor
  function TimeInterval(start, end) {
    this.start = start;
    this.end = end;
  }

  TimeInterval.prototype.toString = function() {
    return this.start + "-" + this.end;
  }

  TimeInterval.prototype.equals = function(that) {
    if (this === that) return true;
    if (!(that instanceof TimeInterval)) return false;
    return this.start.equals(that.start) &&
      this.end.equals(that.end);
  }

  TimeInterval.prototype.overlaps = function(that) {
    if (!(that instanceof TimeInterval))
      throw "bug!";
    if (this.end.smallerNotEqual(that.start)) return false;
    if (that.end.smallerNotEqual(this.start)) return false;
    return true;
  }

  TimeInterval.prototype.merge = function(that) {
    if (!(that instanceof TimeInterval))
      throw "bug!";
    var newStart = this.start.smallerNotEqual(that.start)?
      this.start : that.start;
    var newEnd = this.end.smallerNotEqual(that.end)?
      that.end : this.end;
    return new TimeInterval(newStart, newEnd);
  }

  TimeInterval.delimRE = /\s*(?:to|[-\u2013])\s*/;
  TimeInterval.parse = function(text) {
    var hoursText = text.split(TimeInterval.delimRE);
    var from = HourMinute.parse(hoursText[0]);
    var to = HourMinute.parse(hoursText[1]);

    if (to.hour < from.hour) to.hour += 24;
    return new TimeInterval(from, to);
  }

  TimeInterval.REsrc = "(?:" + HourMinute.REsrc + ")(?:" + 
    TimeInterval.delimRE.source + ")(?:" + HourMinute.REsrc + ")";


  return TimeInterval;
}());

